﻿
using UnityEngine;
using UnityEditor;
using System.IO;
using Newtonsoft.Json;

namespace FastDev
{
    public class LanguageToolEditor : EditorWindow
    {
        private string inputStr = "";
        private string outputStr = "";

        [MenuItem("FastDev/多语言工具")]
        public static void OpenWindow()
        {
            LanguageToolEditor window = (LanguageToolEditor)EditorWindow.GetWindow(typeof(LanguageToolEditor), false, "Language");
            window.Show();
        }

        private void OnGUI()
        {
            GUILayout.Label("输入中文文本:");
            inputStr = GUILayout.TextField(inputStr);

            if (GUILayout.Button("查询/添加"))
            {
                string id = LanguageManager.Instance.RegisterText(inputStr);
                outputStr = id + "\n" + JsonConvert.SerializeObject(LanguageManager.Instance.LanguageDict[id], Formatting.Indented);
                AssetDatabase.Refresh();
            }

            if (GUILayout.Button("移除"))
            {
                LanguageManager.Instance.RemoveText(inputStr);
                AssetDatabase.Refresh();
            }

            if (!string.IsNullOrEmpty(outputStr))
            {
                GUILayout.TextArea(outputStr);
            }


            if (GUILayout.Button("刷新LanguageConstant.cs"))
            {
                CreateLanguageConstant();
            }
        }


        /// <summary>
        /// 创建LanguageConstant.cs
        /// </summary>
        /// <param name="languageDict"></param>
        private static void CreateLanguageConstant()
        {
            var languageDict = LanguageManager.Instance.LanguageDict;

            string path = "./Assets/AutoGenrated/Scripts";
            string classStr = @"
public static class LanguageConstant
{
    $变量
}";
            string var = "";
            foreach (var item in languageDict)
            {
                string txtTag = item.Value.Chinese;
                int maxLength = 6;
                if (txtTag.Length > maxLength)
                    txtTag = $"{txtTag.Substring(0, maxLength)} 省略 {txtTag.Length - maxLength} 字";
                var += $"public const string {txtTag.ToAlphaNumberAndChinese(false).Replace(" ", "_").Replace("\n", "n")} = \"{item.Key}\";\r\n\t";
            }
            classStr = classStr.Replace("$变量", var);

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            File.WriteAllText(path + "/LanguageConstant.cs", classStr);
            AssetDatabase.Refresh();
        }
    }

}
